import React from 'react';
import { useParams } from 'react-router';
import { Link } from 'react-router-dom';
import { ArrowBigLeft, Plus } from 'lucide-react';
import Markdown from 'react-markdown';
import { useTransition } from 'react';

import { Input } from './components/ui/input';
import { Button } from './components/ui/button';
import { Checkbox } from './components/ui/checkbox';

export default function Todos() {
  const params = useParams();
  const tenantId = params.tenantId;

  const [error, setError] = React.useState('');
  const [todos, setTodos] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [tenantName, setTenantName] = React.useState('');
  const [, startTransition] = useTransition();

  React.useEffect(() => {
    fetch(`/api/tenants/${tenantId}/todos`)
      .then((res) => res.json())
      .then((data) => {
        if (Array.isArray(data)) {
          setTodos(data);
        } else {
          setError(data.message);
        }
      });

    fetch(`/api/tenants/${tenantId}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.name) {
          setTenantName(data.name);
        }
        setLoading(false);
      });
  }, [tenantId]);

  if (loading) {
    return 'Loading...';
  }
  return (
    <div className="w-full">
      <div className="mx-auto mt-10 w-[40ch]">
        <div className="text-3xl">{tenantName}'s Todos</div>
        <Link to="/tenants" justifyContent="center">
          <Button variant="link">
            <ArrowBigLeft />
            Back to tenant selection
          </Button>
        </Link>

        {error ? (
          <div className="text-red rounded-xl p-8">⚠️ {error}</div>
        ) : null}
        <form
          className="flex w-full flex-col"
          name="newtodo"
          id="newtodo"
          onSubmit={(event) => {
            event.preventDefault();
            const title = event.currentTarget.elements[1].value; // first element is the button
            handleAdd(title);
          }}
        >
          <div className="flex flex-row gap-2">
            <Button size="icon" type="submit">
              <Plus size={14} />
            </Button>
            <Input
              placeholder="Add task"
              variant="outlined"
              id="todo"
              name="todo"
            />
          </div>
        </form>
        <table className="w-full">
          <caption className="text-sm">
            Estimates are generated by a very smart Llama 🦙 (3.1 405B){' '}
          </caption>
          <thead>
            <tr>
              <th style={{ width: '60%' }}> Task </th>
              <th> AI estimate</th>
            </tr>
          </thead>
          <tbody>
            {todos.map((todo, idx) => (
              <tr key={idx}>
                <td style={{ width: '60%' }}>
                  <div className="flex flex-row items-center gap-4">
                    <Checkbox
                      checked={todo.complete}
                      onCheckedChange={() =>
                        startTransition(() => {
                          completeTodo(tenantId, todo);
                        })
                      }
                    />
                    <div>{todo.title}</div>
                  </div>
                </td>
                <td>
                  <Markdown>
                    {todo.estimate
                      ? String(todo.estimate).replaceAll('\n', '  \n')
                      : 'No estimate found'}
                  </Markdown>{' '}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );

  function handleAdd(title) {
    fetch(`/api/tenants/${tenantId}/todos`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: title,
        complete: false, // new todos are always incomplete
      }),
    })
      .then((resp) => resp.json())
      .then((datum) => {
        setTodos((s) => {
          return [...s, datum];
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  function completeTodo(tenantId, todo) {
    const newComplete = !todo.complete;
    fetch(`/api/tenants/${tenantId}/todos`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        id: todo.id,
        complete: newComplete,
      }),
    })
      .then((resp) => {
        if (resp.status !== 200) {
          throw new Error('Error: ' + resp.message + ' ' + resp.status);
        }
        setTodos((s) => {
          const state = s.slice();
          state.find((t) => t.id === todo.id).complete = newComplete;
          return state;
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }
}
